package org.smr.ministore.security.component.provider;

import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smr.ministore.security.component.exception.PasswordNotRightException;
import org.smr.ministore.security.component.exception.UserNotFoundException;
import org.smr.ministore.security.component.user.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

@Component
public class UsernameAndPasswordAuthenticationProvider implements AuthenticationProvider {

    /**
     * 日志
     */
    private static Logger logger = LoggerFactory.getLogger(UsernameAndPasswordAuthenticationProvider.class);

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String userName = (String) authentication.getPrincipal(); //拿到username
        String password = (String) authentication.getCredentials(); //拿到password

        logger.debug("登录中，用户输入的用户名：　{}，密码：{},",userName, password );


        UserDetails userDetails = userDetailsService.loadUserByUsername(userName);

        if( ObjectUtils.equals(userDetails,null) ){

            logger.debug("用户输入的密码不正确：{},", password );
            throw new UserNotFoundException("用户输入的用户名不正确：" + userName);
        }

        if( ObjectUtils.notEqual(password, userDetails.getPassword()) ){

            logger.debug("用户输入的密码不正确：{},", password );
            throw new PasswordNotRightException("用户输入的密码不正确：" + password);
        }
        return new UsernamePasswordAuthenticationToken (
                userName,
                password,
                userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.equals(UsernamePasswordAuthenticationToken.class);
    }


}
